<template>
  <view class="content">
    <u-navbar title="登录" :is-back="false">
    </u-navbar>
    <image class="bg-img" src="/static/loginBg.jpg"></image>
    <view style="width: 60%;margin: auto;margin-top: 40rpx;margin-bottom: 40rpx">
      <uni-title type="h1" title="智慧校园报修" color="white"></uni-title>
    </view>
    <view class="header">
      <image src="/static/logo.png"></image>
    </view>
    <view class="login-box">

      <view class="uni-padding-wrap uni-common-mt">
        <uni-segmented-control :current="current" :values="items" style-type="text"
                               active-color="#007aff" @clickItem="onClickItem"/>
      </view>
      <view>
        <view v-if="current === 1">
          <view class="list">
            <view class="list-call">
              <image class="img" src="/static/images/public/login/1.png"></image>
              <!-- <input class="sl-input" v-model="username" type="number" maxlength="11" placeholder="输入手机号" /> -->
              <input class="sl-input" v-model="username" type="text" maxlength="11" placeholder="输入用户名"/>
            </view>
            <view class="list-call">
              <image class="img" src="/static/images/public/login/2.png"></image>
              <input class="sl-input" v-model="password" type="text" maxlength="32" placeholder="输入密码" password="true"/>
            </view>

            <view class="button-login" hover-class="button-hover" @tap="bindLogin()">
              <text>登录</text>
            </view>

            <view class="agreenment">
              <navigator url="forget" open-type="navigate">忘记密码</navigator>
              <text>|</text>
              <navigator url="../register/register" open-type="navigate">注册账户</navigator>
            </view>
          </view>


        </view>
        <view v-if="current === 0">
          <view style="width: 70%;margin: auto;margin-top:100rpx">
            <view class="button-login" hover-class="button-hover" @tap="wxLogin()">
              <text>微信授权登录</text>
            </view>
          </view>
        </view>
        <label class="agree" @click="()=>{this.agreeCheck=!this.agreeCheck}">
          <checkbox value="cb" :checked="agreeCheck"  color="#1616efcf" style="transform:scale(0.7)"/>
          我已阅读<text style="color: #319ff3" @click.stop="showPrivacy">《用户隐私保护指引》</text>
        </label>
      </view>


    </view>


    <uni-popup ref="popup" :mask-click="false">
      <view
          style="width: 100%;height: 960rpx;background-color: white;border-radius: 60rpx 60rpx 0 0;padding-bottom: 40rpx">
        <view class="popContent">
          <uni-title type="h2" title="信息绑定" align="center"></uni-title>
          <uni-forms :modelValue="user" ref="form" style="margin-top: 20rpx" :rules="customRules">
            <uni-forms-item name="userType">
              <uni-data-checkbox @change="checkType" style="margin: auto;width: 400rpx;display: block"
                                 v-model="user.userType" :localdata="userTypes"></uni-data-checkbox>
            </uni-forms-item>
            <uni-forms-item name="name">
              <uni-easyinput type="text" v-model="user.name" placeholder="请输入姓名"/>
            </uni-forms-item>
            <uni-forms-item name="nickname">
              <uni-easyinput type="nickname" v-model="user.nickname" placeholder="请输入昵称"/>
            </uni-forms-item>
            <uni-forms-item name="username">
              <uni-easyinput type="text" v-model="user.username" placeholder="请输入用户名(登陆账号)"/>
            </uni-forms-item>
            <uni-forms-item name="password">
              <uni-easyinput type="password" v-model="user.password" placeholder="请输入密码"/>
            </uni-forms-item>
            <uni-forms-item>
              <button @click="submitForm" type="primary" class="bindButton">提交</button>
              <button @click="close" type="error" class="bindButton" style="margin-left: 5%">取消</button>
            </uni-forms-item>
          </uni-forms>

        </view>

      </view>
    </uni-popup>
  </view>
</template>

<script>
import {doLogin} from '@/api/public.js';
import {register} from "@/api/register";
import {getLoginUserInfo} from "@/api/user.js";
import tabBer from "../../../utils/tabBer";
import {Socket} from "@/api/Socket.js";
import {UserService} from "../../../api/user";

export default {
  data() {
    return {
      username: '',
      items: ["微信登陆", "账号密码登陆"],
      current: 0,
      // username:"123456c",
      password: '',
      //是否允许点击登录
      logClick: true,
      wxData: {},
      user: {
        roles: [],
      },
      userTypes: [],
      customRules: {
        name: {
          rules: [{
            required: true,
            errorMessage: '姓名不能为空'
          }]
        },
        username: {
          rules: [{
            required: true,
            errorMessage: '用户名不能为空'
          }]
        },
        password: {
          rules: [{
            required: true,
            errorMessage: '密码不能为空'
          }]
        },
        userType: {
          rules: [{
            required: true,
            errorMessage: '角色不能为空'
          }]
        },
      },
      agreeCheck: false
    };
  },
  onLoad() {
    // this.popOpen()
  },
  created() {
    this.init()
  },
  methods: {
    wxLogin() {
      // console.log(this.agreeCheck)
      if (!this.agreeCheck) {
        uni.showToast({
          title: "请确认阅读隐私政策",
          icon:"none"
        })
        return
      }
      uni.login({
        provider: 'weixin',
        success: (res) => {
          this.wxData.code = res.code;
          // console.log('code', res.code);
          if (res.errMsg == 'login:ok') {
            UserService.wxLogin(this.wxData.code).then((res) => {
              //获取到 openid 和 session_k后，自己的逻辑
              // console.log("resDaa-----",res)
              if (res.data.code == 0) {
                uni.setStorageSync('token', res.data.access_token);
                this.getLoginUserInfo();
              } else {
                //未找到账号
                if (res.data.openId) {
                  this.user.openId = res.data.openId;
                  this.popOpen();
                }
              }
              // DoSomeThing.................
            }).catch(err => {
              console.log("err", err)
              uni.showToast({
                title: '登录失败,请检查网络连接',
                icon: 'none'
              });
            })
          }
        },
      });
    },
    //密码登陆
    bindLogin() {
      if (!this.agreeCheck) {
        uni.showToast({
          title: "请确认阅读隐私政策",
          icon:"none"
        })
        return
      }
      if(this.username&&this.password){
        uni.showToast({
          title: '请输入账号和密码',
          icon: 'none'
        });
      }
      //判断是否允许点击登录按钮
      if (this.logClick) {
        //点击一次变为false
        this.logClick = false
        doLogin({username: this.username, password: this.password, remember: false}).then(res => {
          if (res.data.code === 0) {
            //存token
            uni.setStorageSync('token', res.data.access_token);
            this.getLoginUserInfo();
          } else {
            uni.showToast({
              title: res.data.msg,
              icon: 'none'
            });
            //登录失败1秒后转为true可以登录
            setTimeout(() => {
              this.logClick = true
            }, 1000);
          }
        }).catch(err => {
          uni.showToast({
            title: '登录失败,请检查网络连接',
            icon: 'none'
          });
          //登录失败1秒后转为true可以登录
          setTimeout(() => {
            this.logClick = true
          }, 1000);
        })
      }
    },
    changeLoginType() {
      if (this.loginType == 'wx') {
        this.loginType = 'up'
      } else {
        this.loginType = 'wx'
      }
    },
    getLoginUserInfo() {
      getLoginUserInfo().then(res => {
        if (res.data.code === 0) {
          //查询成功
          // res.data.data.username=this.username;
          //将返回的userinfo存储在store里面
          uni.setStorageSync('userInfo', res.data.data);
          //获取用户类型与展示tabList的交集进行角色确认
          // let tab = Object.keys(tabBer).filter(function (val) { return uni.getStorageSync('userInfo').roles.indexOf(val) > -1 })
          //判断角色是否为空
          // if (tab.length!==0){
          let userType = uni.getStorageSync('userInfo').roles[0]
          if (userType !== null && userType !== '') {
            //设置该角色展示的tabList
            //判断userType是否存在与tabBer里面
            if (tabBer[userType] !== null && tabBer[userType] !== '' && tabBer[userType] !== undefined) {

              uni.setStorageSync('tabList', tabBer[userType]);
              //设置初始化的首页name
              uni.setStorageSync('componentsName', tabBer[userType][0].name);

              var socket = new Socket();
              socket.initWebSocket();
              this.$store.dispatch("SET_SOCKET", socket)
              // uni.setStorageSync('socket', JSON.stringify(socket));
              //进行登录成功提示
              uni.showToast({
                title: '登录成功',
                icon: 'none'
              });

              //成功后延迟0.5秒跳转
              setTimeout(() => {
                uni.redirectTo({
                  url: '../../public/index/index',

                });
              }, 100);
              //登录成功转为true可以登录
              setTimeout(() => {
                this.logClick = true
              }, 50000);
            } else {
              uni.showToast({
                title: '登录失败，请确认是否有登录权限',
                icon: 'none'
              });
              //登录失败1秒后转为true可以登录
              setTimeout(() => {
                this.logClick = true
              }, 1000);
            }
          } else {
            uni.showToast({
              title: '登录失败，请确认是否设置角色',
              icon: 'none'
            });
            //登录失败1秒后转为true可以登录
            setTimeout(() => {
              this.logClick = true
            }, 1000);
          }
        } else {
          //查询失败
          // console.log(res);
          //登录失败1秒后转为true可以登录
          setTimeout(() => {
            this.logClick = true
          }, 1000);
        }
      })
    },
    onClickItem(e) {
      if (this.current !== e.currentIndex) {
        this.current = e.currentIndex
      }
    },
    popOpen() {
      this.$refs.popup.open('bottom')
    },
    close() {
      this.$refs.popup.close()
      this.user={}
    },
    checkType(e) {
      // console.log(e.detail.data)
      this.user.roleIds = [];
      this.user.roleIds.push(e.detail.data.roleId)
    },
    submitForm() {
      this.$refs.form.validate().then(res => {
        // console.log('表单数据信息：', this.user);
        register.registerUser(this.user).then(res => {
          // console.log(res)
          if (res.data.code == 0) {
            //绑定成功,此时应该重新登陆
            uni.showToast({
              title: '绑定成功',
              icon: 'success',
              duration: 2000
            });
            this.close()
            this.wxLogin();
          } else {
            uni.showToast({
              title: '绑定失败',
              icon: 'error',
              duration: 2000
            });
          }
        })
      }).catch(err => {
        console.log('表单错误信息：', err);
      })
    },
    init() {
      UserService.getAllRoles().then(res => {
        // console.log(res)
        let userTypes = [];
        if (res.data.data) {
          res.data.data.forEach(role => {
            if (role.roleCode == 'admin') {
              return
            }
            userTypes.push({
              text: role.roleName,
              value: role.roleCode,
              roleId: role.roleId
            })
          })
        }
        this.userTypes = userTypes;
      })
    },
    showPrivacy(){
      // console.log("show")
      uni.navigateTo({
        url: '/pages/public/mine/privacyAgreement/index'
      });
    }
  }
}
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.header {
  width: 161rpx;
  height: 161rpx;
  /*background: rgb(63, 120, 235);*/
  /*box-shadow: 0rpx 12rpx 13rpx 0rpx rgba(63, 205, 235, 0.47);*/
  /*border-radius: 50%;*/
  margin-top: 30rpx;
  margin-bottom: 30rpx;
  margin-left: auto;
  margin-right: auto;
}

.header image {
  width: 161rpx;
  height: 161rpx;
  /*border-radius: 50%;*/
}

.list {
  display: flex;
  flex-direction: column;
  padding-top: 50rpx;
  padding-left: 70rpx;
  padding-right: 70rpx;
}

.list-call {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  height: 100rpx;
  color: #333333;
  border-bottom: 0.5px solid #e2e2e2;
}

.list-call .img {
  width: 40rpx;
  height: 40rpx;
}

.uni-padding-wrap {
  width: 90%;
  margin: auto;
}

.list-call .sl-input {
  flex: 1;
  text-align: left;
  font-size: 32rpx;
  margin-left: 16rpx;
}

.button-login {
  color: #FFFFFF;
  font-size: 34rpx;
  width: 470rpx;
  height: 100rpx;
  background: linear-gradient(-90deg, rgb(27, 197, 229), rgba(188, 226, 158, 1));
  box-shadow: 0rpx 0rpx 13rpx 0rpx rgba(164, 217, 228, 0.2);
  border-radius: 50rpx;
  line-height: 100rpx;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  margin-top: 60rpx;
}

.button-hover {
  background: linear-gradient(-90deg, rgba(63, 205, 235, 0.8), rgba(188, 226, 158, 0.8));
}

.agreenment {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  font-size: 30rpx;
  margin-top: 35rpx;
  color: #319ff3;
  text-align: center;
  height: 40rpx;
  line-height: 40rpx;
}

.uni-h1 {
  font-size: 70rpx !important;
}

.agreenment text {
  font-size: 24rpx;
  margin-left: 15rpx;
  margin-right: 15rpx;
}

.bg-img {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: -1;
}

.login-box {
  width: 90%;
  background-color: white;
  margin: auto;
  border-radius: 3%;
  padding-top: 50rpx;
  padding-bottom: 50rpx;
}

.popContent {
  width: 90%;
  margin: auto;
  padding: 40rpx 80rpx 80rpx 80rpx;
}

.agree {
  display: block;
  /*margin-left: 70rpx;*/
  margin-top: 40rpx;
  text-align: center;
}
.bindButton{
  display: inline-block;
  width: 45%;
}
</style>
